package goft

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Goft struct {
	*gin.Engine
	g           *gin.RouterGroup
	beanFactory *BeanFactory
}

/**
Igniter 获取Goft
*/
func Igniter() *Goft {
	g := &Goft{Engine: gin.New(), beanFactory: NewBeanFactory()}
	g.Use(ErrorHandler())
	config := InitConfig()
	g.beanFactory.SetBean(config)
	html := config.Server.Html
	if html != "" {
		//var funcMap map[string]interface{}
		//strong := func(txt string) template.HTML {
		//	return template.HTML("<strong>" + txt + "</strong>")
		//}
		//funcMap["Strong"] = strong
		//g.SetFuncMap(funcMap)
		g.LoadHTMLGlob(html)
	}
	return g
}

/**
Launch 运行
*/
func (this *Goft) Launch() {
	var port int32 = 8080
	if config := this.beanFactory.GetBean(new(SysConfig)); config != nil {
		serverConfig := config.(*SysConfig).Server
		port = serverConfig.Port
	}
	this.Engine.Run(fmt.Sprintf(":%d", port))
}

/**
Handle 路由设置
*/
func (this *Goft) Handle(httpMethod, relativePath string, handler interface{}) *Goft {
	if h := Convert(handler); h != nil {
		this.g.Handle(httpMethod, relativePath, h)
	}
	return this
}

/**
Attach 添加中间件
*/
func (this *Goft) Attach(f Fairing) *Goft {
	this.Use(func(context *gin.Context) {
		err := f.OnRequest(context)
		if err != nil {
			context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err})
		} else {
			context.Next()
		}
	})
	return this
}

/**
Beans 工厂注入bean
*/
func (this *Goft) Beans(object ...interface{}) *Goft {
	this.beanFactory.SetBean(object...)
	return this
}

/**
Mount 挂载路由分组
*/
func (this *Goft) Mount(group string, class ...IClass) *Goft {
	//内部逻辑跟 之前极客兔兔七天系列中的group 不一样
	//此处 返回一个新的 *RouterGroup 而非 gin.Engine 里的RouterGroup
	this.g = this.Group(group)
	for _, c := range class {
		c.Bind(this)
		this.beanFactory.inject(c)
	}
	return this
}
